using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Hosting;
using JSC.Portal.Security;
using NHibernate;
using NHibernate.Cfg;
using JSC.Data.NHibernate;
using System.Threading;
using System.Globalization;

namespace JSC.Portal.Web
{
    public class PortalApplication : HttpApplication
	{
        private Dictionary<string, DateTime> _guests;
		private Dictionary<string, DateTime> _authorizedUsers;

		static PortalApplication()
		{
			NHibernateSession.Init(new DirectoryInfo(HostingEnvironment.MapPath("~/App_Data/")));
		}

        public override void Init()
		{
			base.Init();
			this.AuthorizeRequest += new EventHandler(PortalApplication_AuthorizeRequest);
			this.BeginRequest += new EventHandler(PortalApplication_BeginRequest);

			_guests = new Dictionary<string, DateTime>();
			_authorizedUsers = new Dictionary<string, DateTime>();
		}

		
		private void PortalApplication_BeginRequest(object sender, EventArgs e)
		{
            HttpCookie language = Context.Request.Cookies["JSC.Culture"];
            if (language != null)
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(language.Value);

			/// DeleteExpired Authorized Users
			DeleteExpired(_authorizedUsers);
			/// DeleteExpired Guests
			DeleteExpired(_guests);

			string ip = Context.Request.UserHostAddress;
			if (_authorizedUsers.ContainsKey(ip))
			{
				if (_guests.ContainsKey(ip))
					_guests.Remove(ip);
			}
			else
			{
				if (!_guests.ContainsKey(ip))
					_guests.Add(ip, DateTime.Now);
				else
					_guests[ip] = DateTime.Now;
			}
		}

		private void DeleteExpired(Dictionary<string, DateTime> dictionary)
		{
			foreach (string key in dictionary.Keys)
			{
				DateTime date = DateTime.MinValue;
				dictionary.TryGetValue(key, out date);

				TimeSpan tsDifference = date.Subtract(DateTime.Now);
				if (tsDifference.TotalMinutes >= 20)
					dictionary.Remove(key);
			}
		}

		private void PortalApplication_AuthorizeRequest(object sender, EventArgs e)
		{
			if ((Context.User as PortalPrincipal) == null)
				return;
			string ip = Context.Request.UserHostAddress;
			if (!_authorizedUsers.ContainsKey(ip))
				_authorizedUsers.Add(ip, DateTime.Now);
			else
				_authorizedUsers[ip] = DateTime.Now;
		}

		public int GuestsOnline
		{
			get { return _guests.Count; }
		}

		public int AuthorizedUsersOnline
		{
			get { return _authorizedUsers.Count; }
		}
	}
}